package cm.mefobe.android.telecomcost.entities;

import java.util.ArrayList;

import cm.mefobe.android.telecomcost.TelecomCost;

import android.util.Log;

public class Country extends Entity {
	public Country() {
		_type = PROP_TYPE;
	}
	
	

	public Country(long zone_id, String code, int[] _providersIds) {
		super();
		this.zone_id = zone_id;
		this.code = code;
		this._providersIds = _providersIds;
	}

	/**
	 * @param zone_id
	 * @param code
	 */
	public Country(long zone_id, String code) {
		super();
		this.zone_id = zone_id;
		this.code = code;
	}

	private long zone_id;

	private String code;

	private int[] _providersIds;

	public void setCode(String value) {
		this.code = value;
	}

	public String getCode() {
		return code;
	}

	public void setProviderIds(int[] value) {
		this._providersIds = value;
	}

	public int[] getProviderIds() {
		if (_providersIds == null) {
			_providersIds = new int[1];
		}
		return _providersIds;
	}

	public void setZoneId(long zone_id) {
		this.zone_id = zone_id;
	}

	public long getZoneId() {
		return zone_id;
	}

	public static final String PROP_TYPE = "Country";
	
	public static Country allCountry()
	{
		Country allCountry = new Country(-1,"000");
		allCountry.setName("All countries");
		allCountry.setId(-1);
		
		return allCountry;
	}

	public ArrayList<Provider> getProviders() {
		ArrayList<Provider> providers = TelecomCost.getDatabaseManager()
				.getCountryProviders(this);
		return providers;
	}

	public boolean contains(Provider _provider) {
		int index = 0;

		while (index < _providersIds.length) {
			if (_provider.getId() == _providersIds[index]) {
				return true;
			}

			index++;
		}

		return false;
	}

	public boolean add(Provider _provider) {
		if (_providersIds != null) {
			int index = 0;

			while (index < _providersIds.length) {
				if (_provider.getId() == _providersIds[index]) {
					return true;
				}

				index++;
			}

			int[] ids = new int[_providersIds.length + 1];
			index = 0;

			while (index < _providersIds.length) {
				ids[index] = _providersIds[index];
				index++;
			}
			ids[ids.length - 1] = (int) _provider.getId();
			setProviderIds(ids);
		} else {
			_providersIds = new int[1];
			_providersIds[0] = (int) _provider.getId();
		}
		return true;
	}

	public boolean remove(Provider _provider) {
		Log.i("ProviderListActivity",
				"removing provider " + _provider.getName() + " from country "
						+ getName());
		if (_providersIds.length > 0) {
			int[] ids = new int[_providersIds.length - 1];

			int index = 0;
			int j = 0;

			while (index < _providersIds.length) {
				if (_provider.getId() != _providersIds[index]) {
					ids[j] = _providersIds[index];
				}

				j++;
				index++;
			}

			setProviderIds(ids);
		}

		return true;
	}
}
